package com.sxtyxt.online;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Looper;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import com.sxtyxt.entity.User;
import com.sxtyxt.util.ToastUtil;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;


import java.lang.Thread.UncaughtExceptionHandler;
import java.util.LinkedList;
import java.util.List;


public class App extends Application {

    /**
     * 作为系统资源被回收的标记
     */
    public static Boolean isInit = false;
    private static User loginUser = null;
    private static App singleton = null;
    private static RequestQueue mVolleyQueue = null;

    public static App getInstance() {
        if (singleton == null) {
            singleton = new App();
        }
        return singleton;
    }

    public static void setInstance(App app) {
        singleton = app;
    }

    public final void login(User loginUser) {
        App.loginUser = loginUser;
    }

    public final User getLoginUser() {
        if (loginUser == null) {
            loginUser = SystemEnv.getUser();
        }

        return loginUser;
    }

    @Override
    public void onCreate() {

        super.onCreate();

        singleton = this;
        initImageLoader(getApplicationContext());
        // 捕捉异常
//		UnCeHandler catchExcep = new UnCeHandler();
//		Thread.setDefaultUncaughtExceptionHandler(catchExcep);



    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private static List<Activity> activityList = new LinkedList<Activity>();

    /**
     * 添加Activity到activityList
     *
     * @param activity
     */
    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    /**
     * 系统退出时调用
     */
    public static void exit() {

        try {
            for (Activity activity : activityList) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
        } finally {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }

    }

    public static RequestQueue getRequestQueue() {
        if (mVolleyQueue == null) {
            mVolleyQueue = Volley.newRequestQueue(getInstance());
        }
        return mVolleyQueue;
    }

    public static void addRequest(Request<?> req, String tag) {
        req.setTag(tag);
        req.setShouldCache(false);
        getRequestQueue().add(req);
    }

    /**
     * 退出登录,清空数据
     */
    public void logout() {
        loginUser = null;
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        //config.writeDebugLogs(); // Remove for release app
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    public class UnCeHandler implements UncaughtExceptionHandler {

        private Thread.UncaughtExceptionHandler mDefaultHandler;
        public static final String TAG = "CatchExcep";

        public UnCeHandler() {
            // 获取系统默认的UncaughtException处理器
            mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        }

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            if (ex != null) {
                ex.printStackTrace();
            }
            if (!handleException(ex) && mDefaultHandler != null) {
                // 如果用户没有处理则让系统默认的异常处理器来处理
                mDefaultHandler.uncaughtException(thread, ex);
            } else {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.e(TAG, "error : ", e);
                }
                // Intent intent = new Intent(getApplicationContext(),
                // ActWelcome.class);
                // PendingIntent restartIntent =
                // PendingIntent.getActivity(getApplicationContext(), 0, intent,
                // Intent.FLAG_ACTIVITY_NEW_TASK);
                // // 退出程序
                // AlarmManager mgr = (AlarmManager)
                // getSystemService(Context.ALARM_SERVICE);
                // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                // restartIntent); // 1秒钟后重启应用

                // DialogUtil.alertIosDialog(App.activityList.get(0), "title",
                // "message");
                exit();
            }
        }

        /**
         * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
         *
         * @param ex
         * @return true:如果处理了该异常信息;否则返回false.
         */
        private boolean handleException(Throwable ex) {
            if (ex == null) {
                return false;
            }
            // 使用Toast来显示异常信息
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    ToastUtil.getInstance().showToast(App.this,"很抱歉,程序出现异常即将退出");

                    Looper.loop();
                }
            }.start();
            return true;
        }
    }
}
